package org.huzhp.gateway.dynamic.route;

import org.huzhp.gateway.dynamic.ConsoleProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.route.RouteDefinition;
import org.springframework.cloud.gateway.route.RouteDefinitionLocator;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;
import reactor.core.publisher.Flux;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description: 获取管理控制台保存的路由信息
 * @Author: huzp
 * @CreateDate: 2020/3/17 11:45
 * @Version: 1.0
 */
public class ConsoleRouteDefinitionLocator implements RouteDefinitionLocator {

    private static final Logger logger = LoggerFactory.getLogger(ConsoleRouteDefinitionLocator.class);

    private List<RouteDefinition> routeDefinitions = new ArrayList<>();

    private ConsoleProperties consoleProperties;

    private RestTemplate restTemplate;


    public ConsoleRouteDefinitionLocator(ConsoleProperties consoleProperties, RestTemplate restTemplate) {
        this.consoleProperties = consoleProperties;
        this.restTemplate = restTemplate;
    }

    @Override
    public Flux<RouteDefinition> getRouteDefinitions() {
        if (consoleProperties.getRoute() != null && consoleProperties.getRoute().isEnable()) {

            logger.debug("load console gateway routes");

            try {
                GatewayRouteDefinition[] gatewayRouteDefinitions = restTemplate.getForObject(consoleProperties.buildRoutePath(), GatewayRouteDefinition[].class);
                routeDefinitions = Arrays.stream(gatewayRouteDefinitions).map(route -> route.build()).collect(Collectors.toList());
            } catch (RestClientException e) {
                logger.error("load console gateway routes error");
            }
        }
        return Flux.fromStream(routeDefinitions.stream());
    }
}
